#include <odbc/environment.hpp>
#include <odbc/odbc_error.hpp>
#include <cassert>

namespace odbc
{

environment::environment( unsigned int version)
	: handle_( SQL_NULL_HANDLE),
		version_( version)
{
	assert( version > 0);
	try
	{
		// Alloc the handle
		// TODO: is this really working? Passing this object to the exception for diagnostic gathering?
		odbc_error::check_success( 
			SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &handle_),
			*this);

#ifdef _MSC_VER
#pragma warning( push)
#pragma warning( disable: 4312)
#endif
		// Set the odbc version
		odbc_error::check_success(
			SQLSetEnvAttr( handle_, 
							SQL_ATTR_ODBC_VERSION, 
							SQLPOINTER( version_), 
							0),
			*this);
#ifdef _MSC_VER
#pragma warning( pop)
#endif

	}
	catch( ...)
	{
		SQLFreeHandle( SQL_HANDLE_ENV, handle_);
	}
}

// ---------------------------------------------------------------------------------------------------------------------

environment::~environment() throw()
{
	// Dealloc the handle. 
	// In case of error, don't throw exception. 
	// It's not good for library health :)
	SQLFreeHandle( SQL_HANDLE_ENV, handle_);
}

} // namespace odbc
